package com.blocks.mq.producer.example.service;


import com.alibaba.fastjson.JSON;
import com.blocks.mq.producer.entity.Student;
import com.zut.blocks.base.mq.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Topic;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lxd
 * @date 2020/12/4 23:51
 */
@Slf4j
@Service
public class ExampleMqService {

    @Resource
    JmsMessagingTemplate jmsMessagingTemplate;

    @Resource
    ExampleDatabaseService exampleDatabaseService;

    @Resource
    ExampleExcelReadService exampleExcelReadService;

    @Resource
    ExampleTxtReadService exampleReadTxtService;

    @Resource
    @Qualifier("exampleTopic")
    Topic exampleTopic;

    public List<Message> sendStudentAll() {
        List<Student> allStudent = exampleDatabaseService.getAllStudent();
        return allStudent.parallelStream().map(m -> buildMessage(JSON.toJSONString(m), Message.MessageType.database, null)).peek(this::sendMessage).collect(Collectors.toList());
    }

    public Message sendStudent(Integer id) {
        Student student = exampleDatabaseService.getById(id);
        if (student == null) {
            return new Message();
        }
        Message message = buildMessage(JSON.toJSONString(student), Message.MessageType.database, null);
        sendMessage(message);
        return message;
    }

    public Message sendXlsxData(String path) {
        List<List<String>> lists = exampleExcelReadService.readExcel(path);
        Message message = buildMessage(JSON.toJSONString(lists), Message.MessageType.xlsx, path);
        sendMessage(message);
        return message;
    }

    public Message sendTxtData(String path) {
        String s = exampleReadTxtService.readTxtData(path);
        Message message = buildMessage(s, Message.MessageType.txt, path);
        sendMessage(message);
        return message;
    }

    private Message buildMessage(String data, Message.MessageType type, String path) {
        Message message = new Message();
        message.setData(data);
        message.setType(type);
        message.setFilePath(path);
        return message;
    }

    private void sendMessage(final Message message) {
        log.info("thread name: " + Thread.currentThread().getName() + ", send message: " + message);
        jmsMessagingTemplate.convertAndSend(exampleTopic, JSON.toJSONString(message));
    }
}
